#pragma once

#include <CallbackDefine.h>
#include <InetAddress.h>
#include <TcpConnection.h>
#include <event2/listener.h>
#include <event2/event.h>
#include <event2/thread.h>

class Accepter {
public:
	Accepter(event_base* base,socket_t listenFd,int backlog=30);

	Accepter(event_base* base, const InetAddress& listenAddr, int backlog = 30);

	~Accepter();

	bool bind(const InetAddress& addr);

	bool startListen();

	InetAddress getListenAddr() {
		return listenAddr_;
	}

	socket_t getfd();

	std::string getIPv4Address();
	
	uint16_t getPort();

	bool stopListen();

	void setAcceptConnectionCallback(AcceptConnectionCallback cb) {
		acceptConnection_ = cb;
	}

	void onAcceptConnection(socket_t sockfd) {
		if (acceptConnection_) {
			acceptConnection_(sockfd);
		}
	}

private:
	/// <summary>
	/// 传入的InetAddress的address和port可能都是0，因此不能直接使用，而是从listen的socket那里获取真正的address和port
	/// </summary>
	void initAddress();

private:
	int backlog_;
	event_base* base_;
	InetAddress listenAddr_;
	evconnlistener* listener_;
	AcceptConnectionCallback acceptConnection_;
	socket_t listenfd_;
};